//
//  RSWOperation+Login.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/10/24.
//  Copyright © 2016年 com.rs. All rights reserved.
//

#import "RSWDataOperation+Login.h"
#import "RSWDBOperation.h"
#import "ProtocolBase.h"

NSString *const RSWLoginOperationCheckVersionStatusTip = @"版本检查中";

NSString *const RSWLoginOperationStartLoadBaseStatusTip = @"正在为您加载数据，请稍候";

NSString *const RSWLoginOperationFinishLoadBaseStatusTip = @"初始化完成";

NSString *const RSWLoginOperationLoadUserInfoStatusTip = @"加载个人信息数据中";

NSString *const RSWLoginOperationLoadAddressBookStatusTip = @"加载通讯录数据中"; 

NSString *const RSWLoginOperationLoadBaseDataDicStatusTip = @"加载字典数据中";

NSString *const RSWLoginOperationLoadBaseDataMenuStatusTip = @"加载菜单数据中";

NSString *const RSWLoginOperationLoadBaseDataWorkflowStatusTip = @"加载工作流数据中";

@implementation RSWDataOperation(Login) 

- (void)loginByAccount:(NSString*)account password:(NSString*)password completion:(void(^)(NSInteger nResult,NSError *error))completion
{
    EDOMRequestStateType stateType = [super requestAsyncBlock:^
    {
        [self progressViewBegin];
        
        NSInteger thisResult = FALSE;
        NSDictionary *thisDic = nil;
        NSError *thisError = nil;
        
        RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
        if(ser != nil)
        {
            if([_delegate respondsToSelector:@selector(loginStatus:)])
                [(id <XLGLoginCommonProcess>) _delegate loginStatus:XLGLoginCommonProcessLoginingCheckAccountStatusTip];
            
            XLGResult *r = [ser loginByAccount:account password:password];
            
            thisResult = r.outResult;
            thisDic = r.outObj;
            thisError = r.outError;
            
            [self detachDataOperationManager:@[ser]];
            
            NSDictionary *dic = r.outObj;
            XLGLoginAccountInfo *accountInfo = [self readResponseProtocol:dic];
            
            if(thisResult != YES)
                ;
            else if(accountInfo == nil)
                thisResult = NO;
            else
                thisResult = YES;
            
            if(thisResult == YES)
                thisResult = [self loginByLoginAccountInfo:accountInfo password:password];
            
            if(thisResult == YES)
                [self saveMyInfo:dic];
            
            if (TRUE == thisResult && self.isCanRequest)
            {
                BOOL isFirstTRun = [[XLGUserConfig readCurrentUserConfigWithKeys:@[XLGUserConfigIsFirstRun]][XLGUserConfigIsFirstRun] integerValue];
                if (isFirstTRun == YES)
                {
                    thisResult = [self initBasicData];
                }
                
                [self initWorkflow];
                
                RSWDataOperation *manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
                [manager initCurrentUserData];
                
                [self loginEndProcessWithAccount:account];
            }
        }
        
        [self requestResult:thisResult output:nil error:thisError completion:^(NSInteger nResult, id output, NSError *error)
         {
             completion(nResult,error);
         }];
        
        [self progressViewEnd];
    }];
    
    if(stateType == EDOMRequestStateTypeCanNotRequest)
        completion(TERMINATEREADWRITE,nil);
}

- (void)loginOutCompletion:(void(^)(NSInteger nResult))completion
{
   
}

-(XLGResult*)refreshEntAddressBookWithToken:(NSString*)token deptId:(NSString*)deptId
{
    __block NSInteger thisResult =FALSE;
    __block NSMutableArray *thisList = [NSMutableArray new];
    __block NSError *thisError = nil;
    
    RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    XLGResult *r = [ser getEntAddressBookContact:token deptId:deptId];
    
    thisResult = r.outResult;
    thisError = r.outError;
    if(thisResult == YES)
        [thisList addObjectsFromArray:r.outObj];
    
    if(ser != nil)
        [super detachDataOperationManager:@[ser]];
    
    if(thisResult == YES)
    {
        for(NSUInteger i = 0;i < thisList.count;i++)
        {
            EntAddressBookContact *c = thisList[i];
            if(c.userNumber.intValue == [XLGContext context].m_nUsernumber)
            {
                __block MyInfo *myInfo = nil;
                
                if( [MyInfo myInfo] != nil)
                {
                    myInfo = [[MyInfo myInfo] copy];
                }
                else
                {
                    RSWDBOperation *db = [RSWDBOperation new];
                    myInfo = [db getCurrentData].outObj;
                }
                
                if(myInfo == nil)
                    break;
                
                BOOL m = NO;
                
                if([myInfo.userName isEqualToString:c.userName] != YES)
                {
                    myInfo.userName = c.userName;
                    m = YES;
                }
                
                if([myInfo.loginName isEqualToString:c.loginName] != YES)
                {
                    myInfo.loginName = c.loginName;
                    m = YES;
                }
                
                if([myInfo.departmentId intValue] == [c.departmentId intValue])
                {
                    myInfo.departmentName = c.departmentName;
                    myInfo.departmentId = c.departmentId;
                    m = YES;
                }
                
                if([myInfo.logoURL isEqualToString:c.logoURL] !=YES )
                {
                    myInfo.logoURL = c.logoURL;
                    m = YES;
                }
                
                if([myInfo.tel isEqualToString:c.tel] !=YES )
                {
                    myInfo.tel = c.tel;
                    m = YES;
                }
                
                if([myInfo.email isEqualToString:c.email] !=YES )
                {
                    myInfo.email = c.email;
                    m = YES;
                }
                
                if([myInfo.mobilePhone isEqualToString:c.mobilePhone] !=YES )
                {
                    myInfo.mobilePhone = c.mobilePhone;
                    m = YES;
                }
                
                if(m == YES)
                {
                    RSWDBOperation *db = [RSWDBOperation new];
                    [db updateMyInfo:myInfo];
                }
                break;
            }
        }
        
        NSMutableArray *arModify = [NSMutableArray new];
        NSMutableArray *arDelete = [NSMutableArray new];
        
        for(EntAddressBookContact *c in thisList)
        {
            [arModify addObject:c];
        }
        
        RSWDBOperation *db = [RSWDBOperation new];
        if(arModify.count > 0)
        {
            thisResult = [db saveEntAddressBookContact:arModify].outResult;
        }
        if(thisResult == YES && arDelete.count > 0)
        {
            NSArray *ar = [arDelete fetchArrayObjectPorpertyValueWithPorperty:@"userNumber"];
            thisResult = [db deleteEntAddressBookContact:ar].outResult;
        }
    }
    
    if (thisResult == YES && thisList.count > 0)
        [XMSLastUpdateTime setUpdateTime:EntAddressBookLastUpdateTime dateTime:[NSDate date]];
    return [XLGResult resultWithOutResult:thisResult outObj:thisList outError:thisError];
}

-(XLGResult*)refreshDictionaryWithToken:(NSString*)token
{
    __block NSInteger thisResult =FALSE;
    __block NSMutableArray *thisList = [NSMutableArray new];
    __block NSError *thisError = nil;
    
    RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    XLGResult *r = [ser getDicInfo:token];
    
    thisResult = r.outResult;
    thisError = r.outError;
    if(thisResult == YES)
        [thisList addObjectsFromArray:r.outObj];
    
    if(ser != nil)
        [super detachDataOperationManager:@[ser]];
    
    if(thisResult == YES)
    {
        RSWDBOperation *db = [RSWDBOperation new];
        if(thisList.count > 0)
        {
            thisResult = [db saveDicInfo:thisList].outResult;
        }
    }
    
    return [XLGResult resultWithOutResult:thisResult outObj:thisList outError:thisError];
}

-(XLGResult*)refreshMenuWithToken:(NSString*)token
{
    __block NSInteger thisResult =FALSE;
    __block NSMutableArray *thisList = [NSMutableArray new];
    __block NSError *thisError = nil;
    
    RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    XLGResult *r = [ser getMenuInfo:token];
                    
    thisResult = r.outResult;
    thisError = r.outError;
    if(thisResult == YES)
    [thisList addObjectsFromArray:r.outObj];
        
    if(ser != nil)
        [super detachDataOperationManager:@[ser]];
                    
    if(thisResult == YES)
    {
        RSWDBOperation *db = [RSWDBOperation new];
        if(thisList.count > 0)
        {
            thisResult = [db saveMenuInfo:thisList].outResult;
        }
    }
    
    return [XLGResult resultWithOutResult:thisResult outObj:thisList outError:thisError];
}

-(XLGResult*)refreshWorkflowWithToken:(NSString*)token
{
    __block NSInteger thisResult =FALSE;
    __block NSMutableArray *thisList = [NSMutableArray new];
    __block NSError *thisError = nil;
    
    RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    XLGResult *r = [ser getWorkflowInfo:token];
    
    thisResult = r.outResult;
    thisError = r.outError;
    if(thisResult == YES)
        [thisList addObjectsFromArray:r.outObj];
    
    if(ser != nil)
        [super detachDataOperationManager:@[ser]];
    
    if(thisResult == YES)
    {
        RSWDBOperation *db = [RSWDBOperation new];
        if(thisList.count > 0)
        {
            thisResult = [db saveWorkflowInfo:thisList].outResult;
        }
    }
    
    return [XLGResult resultWithOutResult:thisResult outObj:thisList outError:thisError];
}

-(XLGResult*)refreshDeptWithToken:(NSString*)token
{
    __block NSInteger thisResult =FALSE;
    __block NSMutableArray *thisList = [NSMutableArray new];
    __block NSError *thisError = nil;
    
    RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    XLGResult *r = [ser getDeptInfo:token];
    
    thisResult = r.outResult;
    thisError = r.outError;
    if(thisResult == YES)
        [thisList addObjectsFromArray:r.outObj];
    
    if(ser != nil)
        [super detachDataOperationManager:@[ser]];
    
    if(thisResult == YES)
    {
        RSWDBOperation *db = [RSWDBOperation new];
        if(thisList.count > 0)
        {
            thisResult = [db saveDeptInfo:thisList].outResult;
        }
    }
    
    return [XLGResult resultWithOutResult:thisResult outObj:thisList outError:thisError];
}

//private method
- (void)initUserDir
{
    NSInteger nResult = NO;
    
    NSInteger flag = 0; //标记是不是首次登录 1表示首次登录
    NSString *szCreatepath = [XLGContext context].m_szUserpath;
    
    nResult = [XMSFileHelper isFileDirExist:szCreatepath];
    if (nResult != YES)
    {
        flag = 1;
        [XMSFileHelper createDir:[XLGContext context].m_szUserpath];
    }
    
    szCreatepath = [[XLGContext context].m_szUserpath stringByAppendingPathComponent:LOGD];
    nResult = [XMSFileHelper isFileDirExist:szCreatepath];
    if (nResult != YES)
        [XMSFileHelper createDir:szCreatepath];
    
    NSString *ppath = nil;
    NSString *path = [[NSBundle mainBundle] pathForResource:USERCFGF ofType:@"plist"];
    ppath = [[XLGContext context].m_szUserpath stringByAppendingPathComponent:USERCFGFE];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
    {
        [XMSFileHelper copySource:path toTarget:ppath];
    }
    
    if(flag == 1)
        [XLGUserConfig writeCurrentUserConfigWithDictionary:@{XLGUserConfigIsFirstRun:@(YES)}];
    else
        [XLGUserConfig writeCurrentUserConfigWithDictionary:@{XLGUserConfigIsFirstRun:@(NO)}];
  
    [self initUserDir:[XLGContext context].m_szUserpath];
}

- (void)initUserDir:(NSString *)userRootDir
{
    NSString *path = userRootDir;
    
    NSString *p = @"";
    
    NSString *ppath = @"";
    
    ppath = [path stringByAppendingPathComponent:XLGSendQueueDataFolder];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
        [XMSFileHelper createDir:ppath];
    
    p = [[NSBundle mainBundle] pathForResource:[XLGSendQueueDefaultDBFile stringByDeletingPathExtension] ofType:@"db"];
    
    ppath = [path stringByAppendingPathComponent:XLGSendQueueDefaultDBFile];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
        [XMSFileHelper copySource:p toTarget:ppath];
    
    ppath = [path stringByAppendingPathComponent:SendQueueExplicitDBFile];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
        [XMSFileHelper copySource:p toTarget:ppath];
    
    ppath = [path stringByAppendingPathComponent:XLGDownloadDataFolder];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
        [XMSFileHelper createDir:ppath];
    
    p = [[NSBundle mainBundle] pathForResource:[XLGDownloadDBFile stringByDeletingPathExtension] ofType:@"db"];
    
    ppath = [path stringByAppendingPathComponent:XLGDownloadDBFile];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
        [XMSFileHelper copySource:p toTarget:ppath];
    
    
    p = [[NSBundle mainBundle] pathForResource:RSWDBF ofType:@"db"];
    ppath = [path stringByAppendingPathComponent:RSWDBFE];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
        [XMSFileHelper copySource:p toTarget:ppath];
    
    p = [[NSBundle mainBundle] pathForResource:XMSLastUpdateTimeFile ofType:@"plist"];
    ppath = [path stringByAppendingPathComponent:XMSLastUpdateTimeFileExt];
    if ([XMSFileHelper isFileDirExist:ppath] != YES)
        [XMSFileHelper copySource:p toTarget:ppath];
    
    p = [path stringByAppendingPathComponent:HeadImageFolder];
    if ([XMSFileHelper isFileDirExist:p] != YES)
        [XMSFileHelper createDir:p];
    
    p = [path stringByAppendingPathComponent:ChatImageFolder];
    if ([XMSFileHelper isFileDirExist:p] != YES)
        [XMSFileHelper createDir:p];
    
    p = [path stringByAppendingPathComponent:ChatCacheImageFolder];
    if ([XMSFileHelper isFileDirExist:p] != YES)
        [XMSFileHelper createDir:p];
    
    p = [path stringByAppendingPathComponent:ChatSoundFolder];
    if ([XMSFileHelper isFileDirExist:p] != YES)
        [XMSFileHelper createDir:p];
    
    p = [path stringByAppendingPathComponent:SysIconImageFolder];
    if ([XMSFileHelper isFileDirExist:p] != YES)
        [XMSFileHelper createDir:p];
}

- (BOOL)initBasicData
{
    __block NSInteger thisResult = NO;
    
    [RSWDBOperation RSWDBOperationOpen];
    [XMSLastUpdateTime storePath:[XLGContext context].m_szUserdefaulteppath];
    
    [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationStartLoadBaseStatusTip];

    //个人信息
    NSInteger(^f0)()=^NSInteger
    {
        __block NSInteger thisResult = FALSE;
        
        thisResult = YES;
        //thisResult = [self refreshMyInfo];
        
        if([_delegate respondsToSelector:@selector(loginStatus:)])
            [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationLoadUserInfoStatusTip];
        
        return thisResult;
    };
    //部门用户数据
    NSInteger(^f1)()=^NSInteger
    {
        __block NSInteger thisResult = FALSE;
       
        thisResult = [self initEntAddressBook];
        
        if([_delegate respondsToSelector:@selector(loginStatus:)])
            [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationLoadAddressBookStatusTip];
        
        return thisResult;
    };
    //字典表数据
    NSInteger(^f2)()=^NSInteger
    { 
        __block NSInteger thisResult = FALSE;
        
        thisResult = [self initDictionary];
        
        if([_delegate respondsToSelector:@selector(loginStatus:)])
            [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationLoadBaseDataDicStatusTip];
        
        return thisResult;
    };
    //菜单数据
    NSInteger(^f3)()=^NSInteger
    {
        __block NSInteger thisResult = FALSE;
        
        thisResult = [self initMenu];
        
        if([_delegate respondsToSelector:@selector(loginStatus:)])
            [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationLoadBaseDataMenuStatusTip];
        
        return thisResult;
    };
    //部门数据
    NSInteger(^f4)()=^NSInteger
    {
        __block NSInteger thisResult = FALSE;
        
        thisResult = [self initWorkflow];
        
        if([_delegate respondsToSelector:@selector(loginStatus:)])
            [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationLoadAddressBookStatusTip];
        
        return thisResult;
    };
    
    //初始化所有基础数据
    DispatchThreadMultiTask(EDispatchThreadMultiTaskRunTypeGroup, 2, @[f0,f1,f2,f3,f4], ^(NSUInteger taskInindex, NSInteger nResult, BOOL *stop)
                            {
                                thisResult = nResult;
                                
                                if(self.isCanRequest!=YES)
                                    thisResult = TERMINATEREADWRITE;
                                
                                if(thisResult != YES)
                                    *stop = YES;
                            });
    
    if(thisResult == YES)
    {
        if([_delegate respondsToSelector:@selector(loginStatus:)])
            [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationFinishLoadBaseStatusTip];
    }
    
    if(thisResult != YES)
        [RSWDBOperation RSWDBOperationClose];
    
    //test
    //[NSThread sleepForTimeInterval:2];
    
    return YES;
}

-(void)initCurrentUserData
{
    RSWDBOperation *dbo = [RSWDBOperation new];
    XLGResult *r = [dbo getCurrentData];
    
    if(r.outResult == YES && r.outObj != nil)
    {
        [CCurrentUser releaseCurrentUser];
        [CCurrentUser initCurrentUser:r.outObj];
    }
}

- (XLGLoginAccountInfo *)readResponseProtocol:(NSDictionary *)jsonDictionary
{
    XLGLoginAccountInfo * obj;
    if(jsonDictionary != nil)
    {
        XLGLoginAccountInfo *i = [XLGLoginAccountInfo new];
        i.token = jsonDictionary[@"Token"];
        i.account = [jsonDictionary[@"UserID"] stringValue];
        i.loginname = jsonDictionary[@"LoginName"];
        i.externInfo = @{@"DeptName" : jsonDictionary[@"DeptName"],
                         @"Photo" : jsonDictionary[@"Photo"]};
        
        obj = i;
    }
    
    return obj;
}

- (BOOL)saveMyInfo:(NSDictionary *)jsonDictionary
{
    [RSWDBOperation RSWDBOperationOpen];
    
    RSWDBOperation *db = [RSWDBOperation new];
    MyInfo *info = [[MyInfo alloc]init];
    NSString * uStr = jsonDictionary[@"UserID"];
    NSInteger uInt = [uStr integerValue];
    info.userNumber = [XMSNumberInt numberIntWithIntValue:uInt];
    info.loginName = jsonDictionary[@"LoginName"];
    info.userName = jsonDictionary[@"Name"];
    info.logoURL = jsonDictionary[@"Photo"];
    info.mobilePhone = jsonDictionary[@"Mobile"];
    info.email = jsonDictionary[@"Email"];
    info.tel = jsonDictionary[@"TelNo"];
    info.qq = jsonDictionary[@"QQ"];
    NSString *dStr = jsonDictionary[@"DeptID"];
    NSInteger dInt = [dStr integerValue];
    info.departmentId = [XMSNumberInt numberIntWithIntValue:dInt];;
    info.departmentName = jsonDictionary[@"DeptName"];
    
    XLGResult *r = [db updateMyInfo:info];
    
    NSInteger nResult = r.outResult;
    if(nResult == NO)
        [RSWDBOperation RSWDBOperationClose];
    
    return nResult;
}

- (NSInteger)loginByLoginAccountInfo:(XLGLoginAccountInfo*)accountInfo password:(NSString*)password
{
    NSInteger nResult = YES;
    
    [CProtocolBase setProtocolSessionID:accountInfo.token];
    
    [XLGContext context].m_token = accountInfo.token;
    [XLGContext context].m_szAccountno = accountInfo.loginname;
    [XLGContext context].m_szPsw = password;
    [XLGContext context].m_szUsernumber = accountInfo.account;
    [XLGContext context].m_nUsernumber = [[XLGContext context].m_szUsernumber integerValue];
    [XLGContext context].m_szUserpath = [[XMSFileHelper documentPath] stringByAppendingPathComponent:[XLGContext context].m_szUsernumber];
    [XLGContext context].m_bIsoffline = NO;
    [XLGContext context].m_bIsofflinelogin = NO;
    [XLGContext context].m_bLogined = YES;
    [XLGContext context].m_szUserdefaulteppath = [XLGContext context].m_szUserpath;
    
    //nResult = [self checkVersion];
    
    if(nResult == YES)
    {
        [self initUserDir];
        
        if(password.length > 0)
        {
            XLGLoginCommonProcess *um = [XLGLoginCommonProcess new];
            
            [um savePasword:password];
        }
    }
    
    return nResult;
}

-(NSInteger)loginEndProcessWithAccount:(NSString*)account
{
    // 对比最近一次登录信息，做出相应处理。具体机制如下
    // 将szUsernumber和最近一次登录的用户信息进行对比。如果有任意一项与之相同，则认为是上一次的用户再次登录。
    // 此时就在上一次的登录信息中找到真正用于登录的usernumer用于之后的登录操作
    __block NSString *curUserDisplayKey = nil;      //存储当前用户输入的用户名是那种字段，如果为空则说明不是上一次登录过的用户
    NSString *lastUserLoginKey = [XLGContext context].m_dicLastuser[XLGContextLastUserLoginKey];
    NSDictionary *dicLastUserInfo = [XLGContext context].m_dicLastuser[XLGContextLastUserInfo];
    if (lastUserLoginKey.length > 0)
    {
        [dicLastUserInfo enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
         {
             if ([account isEqualToString:obj])
             {
                 curUserDisplayKey = key;
                 *stop = YES;
             }
         }];
    }
    
    NSString *szLoginKey = XLGContextLastUserInfoLoginName;
    
    // 显示key的规则是，如果是上一次的用户再次登录，就把当前用户输入对应的key作为下一次的显示key
    // 否则就用登录key作为显示key
    NSString *szDisplayKey = curUserDisplayKey;
    if (szDisplayKey == nil)
    {
        szDisplayKey = szLoginKey;
    }
    
    NSMutableDictionary *dicUserInfo = [[dicLastUserInfo mutableCopy] autorelease_mm];
    [dicUserInfo setObject:[XLGContext context].m_szUsernumber forKey:XLGContextLastUserInfoUserNum];
    [dicUserInfo setObject:[XLGContext context].m_szAccountno forKey:XLGContextLastUserInfoLoginName];

    NSMutableDictionary *dicLastUser = [[[XLGContext context].m_dicLastuser mutableCopy] autorelease_mm];
    [dicLastUser setObject:szLoginKey forKey:XLGContextLastUserLoginKey];
    [dicLastUser setObject:szDisplayKey forKey:XLGContextLastUserDisplayKey];
    [dicLastUser setObject:dicUserInfo forKey:XLGContextLastUserInfo];
    [XLGContext saveSysCfgValue:dicLastUser forKey:XLGContextLastUser];
    
    return YES;
}

- (BOOL)refreshMyInfo
{
    __block NSInteger thisResult =FALSE;
    
    RSWRESTService *ser = [[RSWRESTService alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    NSString *token = [XLGContext context].m_token;
    
    XLGResult *r = [ser getMyInfo:token];
    
    thisResult = r.outResult;
    if(ser != nil)
        [super detachDataOperationManager:@[ser]];
    
    if(thisResult == YES)
    {
        thisResult = [self saveMyInfo:r.outObj];
        
        if(thisResult == YES)
        {
            [self initCurrentUserData];
        }
    }
    
    return thisResult;
}

- (NSInteger)checkVersion
{
     if([_delegate respondsToSelector:@selector(loginStatus:)])
         [(id <RSWLoginOperationDelegate>) _delegate loginStatus:RSWLoginOperationCheckVersionStatusTip];
    
    NSDictionary *dic = [XLGContext getDocumentSysCfgDictionary][XLGContextUpdateInfo];
    
    XLGResult *r = [XLGCheckNewVersion checkNewVersionAttachDOM:self];
    
    XLGUpdateInfoObj *updateInfo = r.outObj;
    __block NSInteger result = r.outResult;
    
    //强制更新
    if(result == XLGCheckNewVersionForceUpdateCode)
    {
        NSString *newVersionName = updateInfo.versionName;
        
        NSString *tips = [NSString megerStringWithTag:updateInfo.updateInfo tag:@"\r\n"];
        
        [XUIAlertView suspendThreadAlertViewWithTitle:[NSString stringWithFormat:@"发现%@版本",newVersionName] message:tips cancelButtonTitle:@"立即更新" otherButtonTitles:nil clickBlock:^(NSInteger nClickindex)
         {
             [XLGUserConfig writeCurrentUserConfigWithDictionary:@{XLGUserConfigDefaultKeyAutoLogin:@(0)}];
             
             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updateInfo.updateUrl]];
             
             exit(0);
         }];
    }
    //建议更新
    else if(result == XLGCheckNewVersionSuggestUpdateCode)
    {
        BOOL remainUpdate = [dic[XLGContextUpdateInfoRemind] boolValue];
        NSString *oldVername = dic[XLGContextUpdateInfoNewVersionName];
        
        if([oldVername isEqualToString:updateInfo.versionName])
        {
            if(remainUpdate == YES)
            {
                
            }
            else
            {
                result = YES;
            }
        }
        else
        {
            remainUpdate = YES;
        }
        if(remainUpdate == YES)
        {
            NSString *newVersionName = updateInfo.versionName;
            
            NSString *tips = [NSString megerStringWithTag:updateInfo.updateInfo tag:@"\r\n"];
            
            [XUIAlertView suspendThreadAlertViewWithTitle:[NSString stringWithFormat:@"发现%@版本",newVersionName] message:tips cancelButtonTitle:@"立即更新" otherButtonTitles:@[@"以后再说"] clickBlock:^(NSInteger nClickindex)
             {
                 if(nClickindex == 1)
                 {
                     [XLGContext remindNewVersion:NO];
                     result = YES;
                 }
                 else
                 {
                     [XLGUserConfig writeCurrentUserConfigWithDictionary:@{XLGUserConfigDefaultKeyAutoLogin:@(0)}];
                     
                     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updateInfo.updateUrl]];
                     
                     exit(0);
                 }
             }];
        }
    }
    
    return result;
}

- (NSInteger)initEntAddressBook
{
    NSString *token = [XLGContext context].m_token;
    NSString *deptId = [[MyInfo myInfo].departmentId toNSString];
    if(deptId == nil)
        deptId = @"";
    
    RSWDataOperation *manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    
    XLGResult *r = [manager refreshEntAddressBookWithToken:token deptId:deptId];
    
    if(manager != nil)
        [self detachDataOperationManager:[NSArray arrayWithObject:manager]];
    
    NSInteger thisResult = r.outResult;

    return thisResult;
}

- (NSInteger)initDictionary
{
    NSString *token = [XLGContext context].m_token;
    
    RSWDataOperation *manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    
    XLGResult *r = [manager refreshDictionaryWithToken:token];
   
    if(manager != nil)
        [self detachDataOperationManager:[NSArray arrayWithObject:manager]];
    NSInteger thisResult = r.outResult;
    
    return thisResult;
}

- (NSInteger)initMenu
{
    NSString *token = [XLGContext context].m_token;
    
    RSWDataOperation *manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    
    XLGResult *r = [manager refreshMenuWithToken:token];
    
    if(manager != nil)
        [self detachDataOperationManager:[NSArray arrayWithObject:manager]];
    
    NSInteger thisResult = r.outResult;

    return thisResult;
}

- (NSInteger)initWorkflow
{
    NSString *token = [XLGContext context].m_token;
    
    RSWDataOperation *manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:nil AttachDOM:self];
    
    XLGResult *r = [manager refreshWorkflowWithToken:token];
    
    if(manager != nil)
        [self detachDataOperationManager:[NSArray arrayWithObject:manager]];
    
    NSInteger thisResult = r.outResult;
    
    return thisResult;
}

- (void)synDataCompletion:(void(^)(NSInteger nResult,BOOL bResult,NSError *error))completion
{
    [super requestThreadBlock:^
     {
         [super progressViewBegin:@"synData"];
         
         __block NSInteger thisnResult = FALSE;
         __block BOOL thisbResult = FALSE;
         __block NSError *thisError = nil;
         
         thisnResult = [self initBasicData];
         
         [self requestResult:thisnResult output:nil error:thisError completion:^(NSInteger nResult, id output, NSError *error)
          {
              completion(thisnResult,thisbResult,thisError);
          }];
         
         [super progressViewEnd:@"synData"];
     }];
}

-(void)getDictionaryList:(FieldDescript*)fieldDescript completion:(void (^)(NSInteger, NSArray *))completion
{
    NSMutableArray *arr = [NSMutableArray new];
    
    NSString *typeId = [fieldDescript.param valueForKey:Dictionary_TypeId];;
    [self getDictionaryInfoWithTypeId:typeId completion:^(NSInteger nResult, NSArray *list)
     {
         for(DicInfo *w in list)
         {
             SingleSelectInfo *item = [SingleSelectInfo new];
             item.key = [NSString stringWithFormat:@"%@",w.dicId];;
             item.value = w.name;
             
             [arr addObject:item];
         }
         
         completion(nResult,arr);
     }];
}

-(void)getDictionaryInfoWithTypeId:(NSString*)typeId completion:(void (^)(NSInteger nResult, NSArray *list))completion
{
    [super requestThreadBlock:^
     {
         RSWDBOperation *db = [RSWDBOperation new];
         XLGResult *r = [db getDictionaryInfoWithTypeId:typeId];
         
         [super requestResult:r.outResult output:r.outObj completion:completion];
     }];
}
@end
